<template>
  <div class="app-container">
    <el-form class="formList" :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="80px">
      <el-row>
        <el-form-item label="赠品名称" prop="giftName">
          <el-input v-model="queryParams.giftName" placeholder="请输入赠品名称" clearable size="small"
            @keyup.enter.native="handleQuery" />
        </el-form-item>

        <!-- <el-form-item label="领取开始时间" prop="startTime">
          <el-date-picker clearable size="small" v-model="queryParams.startTime" type="date" value-format="yyyy-MM-dd"
            placeholder="选择领取开始时间">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="领取结束时间" prop="endTime">
          <el-date-picker clearable size="small" v-model="queryParams.endTime" type="date" value-format="yyyy-MM-dd"
            placeholder="选择领取结束时间">
          </el-date-picker>
        </el-form-item> -->
        <!-- <el-form-item label="修改时间" prop="updateTime">
          <el-date-picker clearable size="small" v-model="queryParams.updateTime" type="date" value-format="yyyy-MM-dd"
            placeholder="选择修改时间">
          </el-date-picker>
        </el-form-item> -->

        <el-form-item label="状态" prop="dataStatus">
          <el-select v-model="queryParams.dataStatus" placeholder="请选择状态" clearable size="small">
            <el-option v-for="dict in dataStatusOptions" :key="dict.dictValue" :label="dict.dictLabel"
              :value="dict.dictValue" />
          </el-select>
        </el-form-item>

        <!-- <el-form-item label="创建时间" prop="createTime">
          <el-date-picker clearable size="small" v-model="queryParams.createTime" type="date" value-format="yyyy-MM-dd"
            placeholder="选择创建时间">
          </el-date-picker>
        </el-form-item> -->

        <el-form-item >
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>

      </el-row>

    </el-form>

    <el-row class="row-mbinfo">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['activity:gift:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5" style="margin-left: 10px">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['activity:gift:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5" style="margin-left: 10px">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['activity:gift:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5" style="margin-left: 10px">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['activity:gift:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

<div class="divTable">
    <el-table border v-loading="loading" :data="giftList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="赠品ID" align="center" prop="giftUid" /> -->
      <el-table-column label="赠品名称" align="left" prop="giftName" :show-overflow-tooltip="true" width="120">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleShowDetail(scope.row)">{{ scope.row.giftName }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="商品名称" align="left" prop="proName" min-width="200"/>
      <el-table-column label="商品图片" align="center" prop="proImgOne" width="120">
        <template slot-scope="scope">
          <el-image v-if="scope.row.proImgOne != null && scope.row.proImgOne != '' " slot="reference"
                    :src="scope.row.proImgOne"
                    class="image-rows" :preview-src-list="[scope.row.proImgOne]"></el-image>
        </template>
      </el-table-column>
      <el-table-column label="赠品总数" align="center" prop="stockNumber" min-width="80" />
      <el-table-column label="领取次数" align="center" prop="receiveNumber" min-width="80" />
      <el-table-column label="有效天数" align="center" prop="periodValidity" min-width="80" />
      <el-table-column label="领取开始时间" align="center" prop="startTime" min-width="160" sortable>
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="领取结束时间" align="center" prop="endTime" min-width="160" sortable>
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="dataStatus">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.dataStatus" active-value="1" inactive-value="0"
            @change="handleStatusChange(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <!-- <el-table-column label="创建时间" align="center" prop="createTime" width="180" sortable>
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="修改人" align="center" prop="updateName" width="120" />
      <el-table-column label="修改时间" align="center" prop="updateTime" min-width="160" sortable>
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="创建人名称" align="center" prop="createName" :show-overflow-tooltip="true" /> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120" fixed="right">
        <template slot-scope="scope">
          <!-- <el-button size="mini" type="text" icon="el-icon-zoom-in" @click="handleShowDetail(scope.row)"
            v-hasPermi="['activity:gift:query']">查看</el-button> -->
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['activity:gift:edit']">修改</el-button>
          <el-button v-if="scope.row.dataStatus == '0' " size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['activity:gift:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
</div>
    <!-- 添加或修改赠品对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body @keyup.enter.native="submitForm"
     :destroy-on-close="true" @close="hahas">
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="赠品名称" prop="giftName">
          <el-input v-model="form.giftName" placeholder="请输入赠品名称" />
        </el-form-item>

        <el-form-item label="活动商品" prop="proUid">
          <el-button @click="selPro" >选择商品</el-button>
          <!-- 已选商品列表组件-->
          <selectedPro v-if="proTableOpen" @tabRespon="tabFun" :tabList="tabList" :tabUids="tabUids"
           :isShow="isShow" :destroy-on-close="true">
           </selectedPro>
        </el-form-item>

        <el-form-item label="赠品总数" prop="stockNumber">
          <el-input v-model="form.stockNumber" placeholder="请输入赠品总数"  oninput="value=value.replace(/[^\d]/g,'')"  />
        </el-form-item>
        <el-form-item label="有效天数" prop="periodValidity">
          <el-input v-model="form.periodValidity" placeholder="请输入领取后有效天数" oninput="value=value.replace(/[^\d]/g,'')" />
        </el-form-item>
        <el-form-item label="领取开始时间" prop="startTime">
          <el-date-picker clearable size="small" v-model="form.startTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择领取开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="领取结束时间" prop="endTime">
          <el-date-picker clearable size="small" v-model="form.endTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择领取结束时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看赠品对话框 -->
    <el-dialog :title="viewTitle" :visible.sync="viewOpen" width="700px" append-to-body>
      <el-form ref="detailForm" label-width="100px">
        <el-row>
          <el-col :span="12" v-for="(item, index) in showData" :key="index" style="margin-top:-15px">
            <el-form-item :label="`${item.label}：`">
              <span>{{item.value}}</span>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="mini" @click="handCloseDetail">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 选择商品对话框-->
    <el-dialog :title="selTitle" :visible.sync="selOpen" width="1400px" append-to-body :destroy-on-close="true" >
      <productRadio v-if="selOpen" @idsId="idsId" :uids="selUids" ></productRadio>
    </el-dialog>

  </div>
</template>

<script>
  import {
    listGift,
    getGift,
    delGift,
    addGift,
    updateGift,
    updateStatus
  } from "@/api/activity/gift";

  import imageList from "@/components/ImageUpload/imageList";
  import productRadio from '@/components/Product/productRadio';
  import selectedPro from '@/components/Activity/selectedPro';

  export default {
    name: "Gift",
    components: {
      imageList,
      // product,
      selectedPro,
      productRadio
    },
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        names: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 赠品表格数据
        giftList: [],
        // 弹出层标题
        title: "",
        //查看详细标题
        viewTitle: "",
        // 是否显示弹出层
        open: false,
        //是否显示查看详细弹出层
        viewOpen: false,
        //查看详细数据
        showData: [],
        // 状态字典
        dataStatusOptions: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          giftName: null,
          proName: null,
          startTime: null,
          endTime: null,
          dataStatus: null,
          createTime: null,
          updateTime: null,
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          giftName: [
            { required: true, message: "不能为空", trigger: "blur" }
          ],
          proUid: [
            { required: true, message: "不能为空", trigger: "blur" }
          ],
          stockNumber: [
            { required: true, message: "不能为空", trigger: "blur" }
          ],
          periodValidity: [
            { required: true, message: "不能为空", trigger: "blur" }
          ],
          startTime: [
            { required: true, message: "不能为空", trigger: "blur" }
          ],
          endTime: [
            { required: true, message: "不能为空", trigger: "blur" }
          ]
        },
        selOpen:false,
        selTitle:"",
        proTableOpen:false,
        selUids:null,
        tabUids:[],
        isShow:false,
        tabList:[],
        proDa:{
          productUid:null,
          productName:null,
          productImg:null,
          price:null,
          stockNumber:null
        }
      };

    },
    created() {
      this.getList();
      this.getDicts("sys_data_status").then(response => {
        this.dataStatusOptions = response.data;
      });
    },
    //监听路由
    watch: {
      $route(to, from) {
    	//from 从哪来
    	//to //到哪去
    	let path = from.path;
    	if ("/activity/data/" == path) {
    	  //刷新页面
    	  this.getList();
    	} else {
    	  let index = path.lastIndexOf("/");
    	  if (index > -1) {
    		path = path.substr(0, index);
    		if ("/activity/data" == path) {
    		  //刷新页面
    		  this.getList();
    		}
    	  }
    	}
      }
    },
    methods: {
      /** 查询赠品列表 */
      getList() {
        this.loading = true;
        listGift(this.queryParams).then(response => {
          this.giftList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 状态字典翻译
      dataStatusFormat(row, column) {
        return this.selectDictLabel(this.dataStatusOptions, row.dataStatus);
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
        this.proTableOpen = false;
      },
      // 表单重置
      reset() {
        this.form = {
          giftUid: null,
          platformUid: null,
          giftName: null,
          proUid: null,
          proName: null,
          proImg: null,
          periodValidity: null,
          startTime: null,
          endTime: null,
          stockNumber: null,
          receiveNumber: null,
          dataStatus: null,
          createTime: null,
          updateTime: null,
          createUser: null,
          updateUser: null,
          createName: null,
          updateName: null
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.giftUid)
        this.names = selection.map(item => item.giftName)
        this.single = selection.length !== 1
        this.multiple = !selection.length
        //用于禁用删除
        if (this.multiple == false) {
          for (var i = 0; i < selection.length; i++) {
            var element = selection[i];
            if ("1" === element.dataStatus) {
              this.multiple = true;
              break;
            }
          }
        }
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.$router.push({
          path: "/activity/data/",
        });
        // this.reset();
        // this.open = true;
        // this.title = "添加赠品";
      },
      /** 查看详情按钮操作 **/
      handleShowDetail(row) {
        this.$router.push({
          path: "/activity/view/" + row.giftUid,
        });
        // this.viewOpen = true;
        // this.viewTitle = "查看赠品";
        // this.showData = [];
      },
      handCloseDetail() {
        this.viewOpen = false
        this.showData = []
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        const giftUid = row.giftUid;
        this.$router.push("/activity/data/" + giftUid);
        // this.reset();
        // const giftUid = row.giftUid || this.ids
        // getGift(giftUid).then(response => {
        //   this.tabList = [];
        //   this.form = response.data;
        //   //关闭进行局部刷新
        //   this.proTableOpen = false;
        //   //回显选择商品
        //   this.selUids = this.form.proUid;

        //   //回显表格
        //   this.tabUids.push(this.form.proUid);
        //   this.proDa.productUid = this.form.proUid;
        //   this.proDa.productName = this.form.proName;
        //   this.proDa.productImg = this.form.proImg;
        //   this.tabList.push(this.proDa);
        //   //在表格数据加载之后执行
        //   this.$nextTick().then(() => {
        //     this.proTableOpen = true;
        //   })

        //   this.open = true;
        //   this.title = "修改赠品";

        // });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.giftUid != null) {
              updateGift(this.form).then(response => {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
                this.proTableOpen = false;
              });
            } else {
              addGift(this.form).then(response => {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
                this.proTableOpen = false;
              });
            }
          }
        });
      },
      // 状态修改
      handleStatusChange(row) {
        let text = row.dataStatus === "0" ? "无效" : "有效";
        this.$confirm('确定要把赠品名称为"' + row.giftName + '",设为' + text + '吗？', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return updateStatus(row.giftUid, row.dataStatus);
        }).then(() => {
          this.msgSuccess("操作成功");
          this.getList();
        }).catch(function() {
          row.dataStatus = row.dataStatus === "0" ? "1" : "0";
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const giftUids = row.giftUid || this.ids;
        const names = row.giftName || this.names;
        this.$confirm('是否确认删除赠品名称为"' + names + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delGift(giftUids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('activity/gift/export', {
          ...this.queryParams
        }, `activity_gift.xlsx`)
      },
      /** 选择商品组件 */
      selPro(){
        this.selOpen = true;
        this.selTitle = "选择可用商品";
      },
      /** 商品组件选择数据回传 */
      idsId(ids){
        this.$forceUpdate();//强制刷新
        if(ids && ids.productUid){
          this.tabUids = [];
          this.tabList = [];
          this.proTableOpen = false;

          this.selUids = ids.productUid;

          this.tabUids.push(ids.productUid);
          this.tabList.push(ids);

          this.form.proUid = ids.productUid;
          this.form.proName = ids.productName;
          this.form.proImg = ids.productImg;

          this.$nextTick().then(() => {
            this.proTableOpen = true;
          })

        }
        this.selOpen = false;
      },
      /** 已选商品表格数据更新 */
      tabFun(data,v){
        this.selUids = "";
        if(v)
          this.selUids = v[0];//同步已选商品ID
        this.tabUids = v;
        if(data){
          if(data.length==0){
            this.form.proUid = null;
            this.form.proName = null;
            this.form.proImg = null;
            this.proTableOpen = false;
          }else{
            this.form.proUid = data.productUid;
            this.form.proName = data.productName;
            this.form.proImg = data.productImg;
          }
        }
      },
      hahas() {
        this.tabList = [];
        this.selUids = 0;
      }

    }
  };
</script>

<style lang="scss" scoped>
  .image-rows {
    width: 100px;
    height: 100px;
  }
</style>
